package com.itwn.portal.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itwn.common.constant.RedisConst;
import com.itwn.portal.common.exception.Asserts;
import com.itwn.portal.common.result.BusinessCode;
import com.itwn.portal.model.entity.User;
import com.itwn.portal.model.vo.RegisterRequest;
import com.itwn.portal.model.vo.UserVo;
import com.itwn.portal.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Api(tags = "发邮件与注册")
public class EmailController {

    @Autowired
    private UserService userService;
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation("发送邮件接口")
    @GetMapping("/sendEmail")
    public ResponseEntity<?> sendEmail(String email){
        // 校验邮箱不能重复
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getEmail, email));
        Asserts.error(Objects.nonNull(user), BusinessCode.EMAIL_EXIST_ERROR);

        //// 发邮件
        //SimpleMailMessage message = new SimpleMailMessage();
        //message.setSubject("蜗牛书城的验证码");
        //String code = RandomUtil.randomNumbers(4);
        //message.setText("注册验证码是：" + code + ",15分钟有效");
        //message.setFrom(from);
        //message.setTo(email);
        //mailSender.send(message);


        String code = RandomUtil.randomNumbers(4);
        // 构造消息数据
        Map<String,Object> map = new HashMap<>();
        map.put("from",from);
        map.put("to",email);
        map.put("subject","蜗牛书城的验证码");
        map.put("content","注册验证码是：" + code + ",15分钟有效");
        // 发送mq消息
        rabbitTemplate.convertAndSend("email.queue",map);


        // 验证码保存到Redis中
        stringRedisTemplate.opsForValue().set(
                RedisConst.EMAIL_ADDRESS_PREFIX + ":" + ""+email, code, Duration.ofMinutes(15));

        return ResponseEntity.ok("验证码发送成功，请查收！");
    }


    // 要求：注册成功，自动登录！
    @ApiOperation("注册")
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request){
        UserVo userVo = userService.register(request);
        return ResponseEntity.ok()
                .header("Authorization", userVo.getToken())
                //告知浏览器可以访问 Authorization 响应头，否则访问不了
                .header("Access-Control-Expose-Headers", "Authorization")
                .body(userVo);
    }
}
